import {get} from '../utils/http';
import {API_GET_PAYMENT_STATUS, API_PAY_COURSE, PAY_ERROR, urlFormat} from '../common/constants';
import toast from '../common/service/toast-service';

// 获取支付状态
// {courseId: id}
exports.getPaymentStatus = (courseId, isFree) => {
    return new Promise((resolve, reject) => {
        get(urlFormat(API_GET_PAYMENT_STATUS, {courseId: courseId}))
            .then(payStatus => {
                let data = {};
                data.isFree = isFree;
                data.payStatus = payStatus;
                resolve(data);
            }, error => {
                console.log('获取支付状态失败');
                error.errorCode = PAY_ERROR.GET_PAY_STATUS_ERR;
                reject(error);
            });
    });
};

// 发起课程支付
exports.payCourse = (courseId) => {
    return new Promise((resolve, reject) => {
        get(urlFormat(API_PAY_COURSE, {courseId: courseId}))
            .then(data => resolve(data), error => {
                if (error.statusCode === 811) {
                    console.log('重复购买');
                    error.errorCode = PAY_ERROR.REPEAT_PURCHASES;
                } else {
                    console.log('获取支付对象失败');
                    toast.showLoadingToast('服务器请求失败');
                    error.errorCode = PAY_ERROR.GET_PAY_OBJ_ERR;
                }
                reject(error);
            });
    });
};
